//
//  MCGameRecordViewController.m
//  TLYL
//
//  Created by miaocai on 2017/7/10.
//  Copyright © 2017年 TLYL01. All rights reserved.
//

#import "MCGameRecordViewController.h"
#import "MCGameRecordTableViewCell.h"
#import "MCGameRecordDetailViewController.h"
#import "MCGameRecordMineFilterView.h"
#import "MCNaviButton.h"
#import "DatePickerView.h"
#import "MCNaviPopView.h"
#import "MJRefresh.h"
#import "MCGameRecordModel.h"
#import "MCNoDataWindow.h"
#import "MCNONetWindow.h"
#import "MCErrorWindow.h"
#import "MCChaseNumberViewController.h"
#import "MCPickNumberViewController.h"


@interface MCGameRecordViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>


@property (nonatomic,weak) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *tableViewDataArray;
@property (nonatomic,weak) MCGameRecordMineFilterView *filterView;
@property (nonatomic,weak) DatePickerView  *datePicker;
@property (nonatomic,weak) MCNaviPopView *popView;
@property (nonatomic,weak) MCNaviPopView *recordPopView;
@property (nonatomic,weak) MCNaviPopView *allPopView;
@property (nonatomic,strong) NSString *sourceCode;
@property (nonatomic,strong) NSString *lotteryCode;
@property (nonatomic,assign) BOOL isHistory;
@property (nonatomic,strong) NSString *insertTimeMin;
@property (nonatomic,strong) NSString *insertTimeMax;
@property (nonatomic,strong) NSString *currentPageIndex;
@property (nonatomic,strong) NSString *currentPageSize;
@property (nonatomic,strong) NSDate *minDate;
@property (nonatomic,strong) NSDate *maxDate;
@property (nonatomic,strong) MCGameRecordModel *gameRecordModel;
@property (nonatomic,assign) int index;
@property (nonatomic,weak) MCNaviButton *btn;
@property (nonatomic,weak) MCNoDataWindow *dataWind;


@end





@implementation MCGameRecordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"游戏记录";
    [self addNavRightBtn];
    [self setUpUI];
    self.index = 1;
    [self configRequstNormalParmas];
    
    [self loadDataAndShow:self.lotteryCode];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadDataAndShow) name:@"MCErrorWindow_Retry" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadDataAndShow) name:@"MCNONetWindow_Retry" object:nil];

    UITapGestureRecognizer *singleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closePop:)];
    singleTapGesture.numberOfTapsRequired = 1;
    singleTapGesture.cancelsTouchesInView = NO;
    [self.dataWind addGestureRecognizer:singleTapGesture];
    [self.tableView addGestureRecognizer:singleTapGesture];
}

#pragma mark - gesture actions
- (void)closePop:(UITapGestureRecognizer *)recognizer {
    
    [self.popView hidePopView];
    [self.recordPopView hidePopView];
    
}
-(void)loadDataAndShow{
    [self loadDataAndShow:@""];
}
- (void)configRequstNormalParmas{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy/MM/dd"];
    NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
    self.minDate = [NSDate dateWithTimeIntervalSinceNow:-3 * 3600 * 24];
    self.maxDate = [NSDate date];
    self.sourceCode = @"1";
    self.lotteryCode = @"";
    self.isHistory = false;
    self.insertTimeMin = currentDateStr;
    self.insertTimeMax = currentDateStr;
    self.currentPageIndex = @"1";
    self.currentPageSize = @"10";

}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=NO;
    self.navigationController.navigationBar.translucent = NO;
//    self.currentPageIndex = @"1";
//    self.index=1;
//    [self.tableViewDataArray removeAllObjects];
//    [self loadDataAndShow:self.lotteryCode];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.dataWind hideModelWindow];
    [self.popView hidePopView];
    [self.recordPopView hidePopView];
    [self.allPopView hidePopView];
    [[MCNONetWindow alertInstance] hideModelWindow];
    [[MCErrorWindow alertInstance] hideModelWindow];
    if ([self.navigationController.viewControllers.lastObject isKindOfClass:[MCChaseNumberViewController class]] || [self.navigationController.viewControllers.lastObject isKindOfClass:[MCPickNumberViewController class]]) {
        [self.navigationController popToRootViewControllerAnimated:YES];
        self.tabBarController.selectedIndex = 3;
    }
   
}

- (BOOL)bissextile:(int)year {
    
    if ((year%4==0 && year %100 !=0) || year%400==0) {
        return YES;
    }else {
        return NO;
    }
    return NO;
}

- (void)addNavRightBtn {
    
    MCNaviButton *btn = [[MCNaviButton alloc] init];
    [btn setImage:[UIImage imageNamed:@"tab_Title_drop_dpwn"] forState:UIControlStateNormal];
    [btn setTitle:@"全部彩种" forState:UIControlStateNormal];
    self.btn = btn;
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    [btn sizeToFit];
    [btn addTarget:self action:@selector(allBtnClick:) forControlEvents:UIControlEventTouchDown];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)setUpUI{
    self.automaticallyAdjustsScrollViewInsets =NO;
    self.view.backgroundColor = [UIColor whiteColor];
    UIScrollView *baseScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, G_SCREENWIDTH, G_SCREENHEIGHT - 128)];
    [self.view addSubview:baseScrollView];
    baseScrollView.contentSize = CGSizeMake(G_SCREENWIDTH * 4, G_SCREENHEIGHT - 128);
    baseScrollView.pagingEnabled = YES;
    /**tabView 创建*/

    UITableView *tab = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, G_SCREENWIDTH, G_SCREENHEIGHT - 128) style:UITableViewStylePlain];
    [baseScrollView addSubview:tab];
    baseScrollView.delegate = self;
    tab.delegate = self;
    tab.dataSource = self;
    self.tableView = tab;
    self.tableView.backgroundColor=[UIColor whiteColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = MC_REALVALUE(143);
    [self.tableView registerClass:[MCGameRecordTableViewCell class] forCellReuseIdentifier:@"MCGameRecordTableViewCell"];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];

    MCGameRecordMineFilterView *filterView = [[MCGameRecordMineFilterView alloc] initWithFrame:CGRectMake(0, 0, G_SCREENWIDTH, 64)];
    self.filterView = filterView;
    __weak typeof(self) weakself = self;
    __weak MCGameRecordMineFilterView *weakFilter = filterView;
    
    filterView.recordBtnBlock = ^{
        
        weakself.recordPopView.dataSourceArray = @[@"当前记录",@"历史记录"];
        weakself.recordPopView.frame= CGRectMake(0, 108, G_SCREENWIDTH/3, 50);
        [weakself.recordPopView showPopView];
        
    };
    
    self.recordPopView.recordSelectedBlock = ^(NSInteger i) {
        [filterView.recordBtn setTitle:self.recordPopView.dataSourceArray[i] forState:UIControlStateNormal];
        if (i == 0) {
            
            weakself.minDate = [NSDate dateWithTimeIntervalSinceNow:-3 * 3600 * 24];
            weakself.maxDate = [NSDate date];
            self.isHistory = NO;
        } else {
            
            NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
            
            NSDateComponents *comps = nil;
            
            comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:[NSDate date]];
            NSArray *arrMouth = nil;
            
            if ([self bissextile:(int)[comps year]]) {
                arrMouth = @[@31,@29,@31,@30,@31,@30,@31,@31,@30,@31,@30,@31];
            } else {
                arrMouth = @[@31,@28,@31,@30,@31,@30,@31,@31,@30,@31,@30,@31];
            }
            NSNumber * mo = arrMouth[comps.month - 1];
            
            weakself.minDate = [NSDate dateWithTimeIntervalSinceNow:- ([mo intValue ]+ 3) * 3600 * 24];
            weakself.maxDate = [NSDate dateWithTimeIntervalSinceNow:-4 * 3600 * 24];
            self.isHistory = YES;
        }
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy/MM/dd"];
        NSString *endDateStr = [dateFormatter stringFromDate:weakself.maxDate];
        [filterView.startTimeBtn setTitle:endDateStr forState:UIControlStateNormal];
        [filterView.endTimeBtn setTitle:endDateStr forState:UIControlStateNormal];
        self.insertTimeMin = endDateStr;
        self.insertTimeMax = endDateStr;
        [self loadDataAndShow:self.lotteryCode];
    };
    
    
    filterView.startDateBlock = ^{
        
        weakself.datePicker.cancelBlock = ^{
            
            [UIView animateWithDuration:0.25 animations:^{
                [weakself.datePicker removeFromSuperview];
            }];
        };
        
        weakself.datePicker.sureBlock = ^(NSString *selectDateStr) {
            [weakFilter.startTimeBtn setTitle:selectDateStr forState:UIControlStateNormal];
//            self.insertTimeMax = selectDateStr;
            self.insertTimeMin = selectDateStr;
            [self loadDataAndShow:self.lotteryCode];
            [UIView animateWithDuration:0.25 animations:^{
                [weakself.datePicker removeFromSuperview];
                
            }];
        };
        
        
    };
    filterView.endDateBlock = ^{
        weakself.datePicker.cancelBlock = ^{
            [UIView animateWithDuration:0.25 animations:^{
                [weakself.datePicker removeFromSuperview];
            }];
        };
        weakself.datePicker.sureBlock = ^(NSString *selectDateStr) {
            [weakFilter.endTimeBtn setTitle:selectDateStr forState:UIControlStateNormal];
            self.insertTimeMax = selectDateStr;
            [self loadDataAndShow:self.lotteryCode];
            [UIView animateWithDuration:0.25 animations:^{
                [weakself.datePicker removeFromSuperview];
            }];
        };
    };
    
    [self.view addSubview:filterView];
}
- (void)loadMoreData{
    
    self.gameRecordModel->_currentPageIndex = [NSString stringWithFormat:@"%d",++self.index];
    __block typeof(self) weakSelf = self;
    self.gameRecordModel.callBackSuccessBlock = ^(id manager) {
        
        NSArray *arr = [MCGameRecordModel mj_objectArrayWithKeyValuesArray:manager[@"BtInfo"]];
        [weakSelf.tableViewDataArray addObjectsFromArray:arr];
        if (weakSelf.tableViewDataArray.count == 0) {
            [weakSelf.dataWind showModelWindow];
        }else{
            [weakSelf.dataWind hideModelWindow];
        }
//        weakSelf.filterView.totalLabel.text = [NSString stringWithFormat:@"记录总数：%ld条",weakSelf.tableViewDataArray.count];
        weakSelf.filterView.totalLabel.text = [NSString stringWithFormat:@"记录总数：%@条",manager[@"DataCount"]];
        
        [weakSelf.tableView reloadData];
        [weakSelf.tableView.mj_footer endRefreshing];
        if (weakSelf.tableViewDataArray.count==[manager[@"DataCount"] integerValue]) {
            weakSelf.tableView.mj_footer.hidden=YES;
        }
    };
    
    [self.gameRecordModel refreashDataAndShow];
}

- (void)allBtnClick:(UIButton *)btn{
    
  
 
   NSArray *arr = @[
                    
    @{
       @"name": @"全部彩种",
       @"lotteryId": @""
        },
     @{
       @"name": @"天利1分彩",
       @"lotteryId": @"51"
       
       },
     @{
       @"name": @"天利3分彩",
       @"lotteryId": @"53"
       
       },
     @{
       @"name": @"天利5分彩",
       @"lotteryId": @"55"
       
       },
     @{
       @"name": @"极限秒秒彩",
       @"lotteryId": @"50"
       
       },
     @{
       @"name": @"重庆时时彩",
       @"lotteryId": @"12"
       },
     @{
       @"name": @"天津时时彩",
       @"lotteryId": @"71"
       
       },
     @{
       @"name": @"新疆时时彩",
       @"lotteryId": @"14"
       
       },
     @{
       @"name": @"老韩国1.5分彩",
       @"lotteryId": @"72"
       
       },
     @{
       @"name": @"韩国1.5分彩",
       @"lotteryId": @"56"
       
       },
     @{
       @"name": @"东京1.5分彩",
       @"lotteryId": @"75"
       
       },
     @{
       @"name": @"台湾五分彩",
       @"lotteryId": @"73"
       
       },
     @{
       @"name": @"加拿大3.5分彩",
       @"lotteryId": @"76"
       
       },
     @{
       @"name": @"新加坡2分彩",
       @"lotteryId": @"74"
       
       },
     @{
       @"name": @"腾讯分分彩",
       @"lotteryId": @"57"
       
       },
     @{
       @"name": @"QQ分分彩",
       @"lotteryId": @"58"
       
       },
     @{
       @"name": @"北京时时彩",
       @"lotteryId": @"86"
       
       },
     @{
       @"name": @"菲律宾1.5分彩",
       @"lotteryId": @"66"
       
       },
     @{
       @"name": @"11选5分分彩",
       @"lotteryId": @"61"
       
       },
     @{
       @"name": @"11选5三分彩",
       @"lotteryId": @"63"
       },
     @{
       @"name": @"广东11选5",
       @"lotteryId": @"4"
       
       },
     @{
       @"name": @"江西11选5",
       @"lotteryId": @"5"
       },
     @{
       @"name": @"上海11选5",
       @"lotteryId": @"77"
       
       },
     @{
       @"name": @"安徽11选5",
       @"lotteryId": @"78"
       
       },
     @{
       @"name": @"山东11选5",
       @"lotteryId": @"16"
       
       },
     @{
       @"name": @"江苏11选5",
       @"lotteryId": @"85"
       
       },
     @{
       @"name": @"福彩3D",
       @"lotteryId": @"19"
       
       },
     @{
       @"name": @"3D分分彩",
       @"lotteryId": @"84"
       
       },
     @{
       @"name": @"排列三",
       @"lotteryId": @"17"
       
       },
     @{
       @"name": @"排列五",
       @"lotteryId": @"18"
       
       },
     @{
       @"name": @"上海时时乐",
       @"lotteryId": @"15"
       
       },
     @{
       @"name": @"北京快乐8",
       @"lotteryId": @"9"
       
       },
     @{
       @"name": @"韩国快乐8",
       @"lotteryId": @"79"
       
       },
     @{
       @"name": @"台湾快乐8",
       @"lotteryId": @"80"
       
       },
     @{
       @"name": @"北京PK拾",
       @"lotteryId": @"10"
       
       },
     @{
       @"name": @"江苏快3",
       @"lotteryId": @"26"
       
       },
     @{
       @"name": @"吉林快3",
       @"lotteryId": @"81"
       
       },
     @{
       @"name": @"安徽快3",
       @"lotteryId": @"82"
       
       },
     @{
       @"name": @"湖北快3",
       @"lotteryId": @"83"
       
       }
//     @{
//       @"name": @"江苏骰宝",
//       @"lotteryId": @"21"
//       
//       },
//     @{
//       @"name": @"吉林骰宝",
//       @"lotteryId": @"87"
//       
//       },
//     @{
//       @"name": @"安徽骰宝",
//       @"lotteryId": @"88"
//       
//       },
//     @{
//       @"name": @"湖北骰宝",
//       @"lotteryId": @"89"
//       }
     ];
    NSMutableArray *arrTemp = [NSMutableArray array];
    for (NSDictionary *dic in arr) {
        [arrTemp addObject:dic[@"name"]];
    }
    
    MCNaviPopView * popView = [[MCNaviPopView alloc] init];
    [self.navigationController.view addSubview:popView];
    self.allPopView = popView;
    self.allPopView.dataSourceArray = arrTemp;
    self.allPopView.frame= CGRectMake(G_SCREENWIDTH-110, 64, 110, 110);
    [self.allPopView showPopView];
    __weak typeof(self) weakself = self;
    self.allPopView.recordSelectedBlock = ^(NSInteger index) {
      NSDictionary *dic = arr[index];
        [weakself.btn setTitle:dic[@"name"] forState:UIControlStateNormal];
        [weakself.btn sizeToFit];

        [weakself loadDataAndShow:dic[@"lotteryId"]];
    };
}

- (void)loadDataAndShow:(NSString *)lotteryCode{
    self.tableView.mj_footer.hidden=NO;
    self.gameRecordModel->_sourceCode = @"1";
    self.gameRecordModel->_lotteryCode = lotteryCode;
    self.gameRecordModel->_isHistory = self.isHistory;
    self.gameRecordModel->_insertTimeMin = [NSString stringWithFormat:@"%@ 00:00:00",self.insertTimeMin];
    NSString *str = [NSString stringWithFormat:@"%@ 23:59:59",self.insertTimeMax];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT+0800"];
    [dateFormatter setTimeZone:timeZone];
    NSDate *date = [dateFormatter dateFromString:str];
    NSComparisonResult result = [date compare:[NSDate date]];
    
    if (result == NSOrderedDescending) {
        
        self.gameRecordModel->_insertTimeMax = [dateFormatter stringFromDate:[NSDate date]];
    }else{
        self.gameRecordModel->_insertTimeMax = [NSString stringWithFormat:@"%@ 23:59:59",self.insertTimeMax];
    }
    self.gameRecordModel->_currentPageIndex = self.currentPageIndex;
    self.gameRecordModel->_currentPageSize = @"10";
    __block typeof(self) weakSelf = self;
    
    self.gameRecordModel.callBackSuccessBlock = ^(id manager) {
        
        if ([manager isKindOfClass:[NSString class]]) {
            [weakSelf.tableViewDataArray removeAllObjects];
//            weakSelf.filterView.totalLabel.text = [NSString stringWithFormat:@"记录总数：%ld条",weakSelf.tableViewDataArray.count];
            weakSelf.filterView.totalLabel.text = [NSString stringWithFormat:@"记录总数：%@条",manager[@"DataCount"]];
            
            [weakSelf.tableView.mj_footer endRefreshing];
            [weakSelf.tableView reloadData];
            return ;
        }
        weakSelf.tableViewDataArray = [MCGameRecordModel mj_objectArrayWithKeyValuesArray:manager[@"BtInfo"]];
        MCNoDataWindow *dataWind = [MCNoDataWindow alertInstanceWithFrame:CGRectMake(0, 188, G_SCREENWIDTH, G_SCREENHEIGHT - 128 - 200 - 60)];
        if (weakSelf.tableViewDataArray.count == 0) {
            [dataWind showModelWindow];
        }else{
            [dataWind hideModelWindow];
        }
        weakSelf.dataWind = dataWind;
//        weakSelf.filterView.totalLabel.text = [NSString stringWithFormat:@"记录总数：%ld条",weakSelf.tableViewDataArray.count];
        weakSelf.filterView.totalLabel.text = [NSString stringWithFormat:@"记录总数：%@条",manager[@"DataCount"]];
        if (weakSelf.tableViewDataArray.count==[manager[@"DataCount"] integerValue]) {
            weakSelf.tableView.mj_footer.hidden=YES;
        }
        [weakSelf.tableView reloadData];
    };
    
    [self.gameRecordModel refreashDataAndShow];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    int index = scrollView.contentOffset.x/G_SCREENWIDTH;
    [self.filterView changeBtnStatus:index];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.tableViewDataArray.count;//self.tableViewDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MCGameRecordTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MCGameRecordTableViewCell"];
    cell.dataSource = self.tableViewDataArray[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MCGameRecordDetailViewController *vc = [[MCGameRecordDetailViewController alloc] init];
    vc.dataSource = self.tableViewDataArray[indexPath.row];
    vc.isHistory = self.isHistory;
    [self.navigationController pushViewController:vc animated:YES];
}
- (NSMutableArray *)tableViewDataArray{
    
    if (_tableViewDataArray == nil) {
        _tableViewDataArray = [NSMutableArray array];
    }
    return _tableViewDataArray;
}

- (DatePickerView *)datePicker{
    
    if (_datePicker == nil) {
        DatePickerView *datePicker =[[[NSBundle mainBundle] loadNibNamed:@"DatePickerView" owner:self options:0] lastObject];
        datePicker.minDate = self.minDate;
        datePicker.maxDate = self.maxDate;
        datePicker.frame =CGRectMake(0, self.view.frame.size.height  - 200, self.view.frame.size.width, 200);
        datePicker.Datetitle =@"日期选择";
        [self.view addSubview:datePicker];
        _datePicker = datePicker;
    }
    return _datePicker;
}
- (MCNaviPopView *)popView{
    
    if (_popView == nil) {
        MCNaviPopView * popView = [[MCNaviPopView alloc] init];
        [self.navigationController.view addSubview:popView];
        _popView = popView;
    }
    return _popView;
}
- (MCNaviPopView *)recordPopView{
    
    if (_recordPopView == nil) {
        MCNaviPopView * popView = [[MCNaviPopView alloc] init];
        [self.navigationController.view addSubview:popView];
        _recordPopView = popView;
    }
    return _recordPopView;
}

- (MCGameRecordModel *)gameRecordModel{
    if (_gameRecordModel == nil) {
        MCGameRecordModel *model = [[MCGameRecordModel alloc] init];
        _gameRecordModel = model;
    }
    return _gameRecordModel;
}
@end
